#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from ParseExcel import ParseExcel
from Logger import logger
from itertools import groupby
from Timer import timer
import re


class CheckExcel(ParseExcel):
    """检查Excel表格的配置项是否合规"""
    @timer(tracer=True)
    def check_dup_id(self, xpath, sheet_name=None):
        """
        检查指定sheet页中指定xpath的元素的ID是否会重复
        :param xpath: list类型，所查元素的xpath
        :param sheet_name: list类型，所查元素所在的表名，如果为None，则代表全部表单
        :return: None
        """
        xpath_list, sheet_name_list = list(), list()
        if isinstance(xpath, str):
            xpath_list = [xpath]
        elif isinstance(xpath, list):
            xpath_list = xpath

        if isinstance(sheet_name, str):
            sheet_name_list = [sheet_name]
        elif isinstance(sheet_name, list):
            sheet_name_list = sheet_name
        else:
            sheet_name_list = self.worksheet_names

        attr_list = self.attr_group
        attr_list = list(filter(lambda d: 'SheetName' in d and '>>XPath' in d, attr_list))
        attr_list = list(filter(lambda d: d['SheetName'] in sheet_name_list and d['>>XPath'] in xpath_list, attr_list))

        dup_element_list = list()
        for attrs in attr_list:
            dup_element_dict = dict()
            re_key, key = '^[iI][dD]$', None
            for k in attrs:
                key = re.match(re_key, k)
                if key:
                    ab_key = key.group()
                    dup_element_dict['{0}第{1}行'.format(attrs['SheetName'], attrs['RowNum'])] = attrs[ab_key]
                    dup_element_list.append(dup_element_dict)

        dup_element_list, dup = list(sorted(dup_element_list, key=lambda d: int(list(d.values())[0]))), True
        for _id, items in groupby(dup_element_list, key=lambda d: list(d.values())[0]):
            items_list = list(items)
            if len(items_list) > 1:
                dup = False
                for item in items_list:
                    logger.error('工作簿[{0}][{1}]有重复ID:[{2}]'.format(self.file_path, list(item.keys())[0], _id))
        if dup:
            logger.info('工作簿[{0}]没有重复ID'.format(self.file_path))


if __name__ == '__main__':
    logger.info('start')
    path = r'E:\Workspace\Projects\GDTools\ExcelToXml\ShopConfig.xlsx'
    excel = CheckExcel(path)
    excel.check_dup_id(xpath=['>>Config/BallEquipment/item'], sheet_name=['Sheet2'])
    logger.info('end')
